//
//  YSMainTabBarController.m
//  YouSheng
//
//  Created by aaa on 16/8/17.
//  Copyright © 2016年 FanShuHan. All rights reserved.
//

#import "YSMainTabBarController.h"
#import "YSNavigationAnimator.h"
#import "YSNavigationHandler.h"
#import "YSDialViewController.h"
#import "YSChatViewController.h"
#import "YSContactsViewController.h"
#import "YSMeViewController.h"
#import "YSCustomNotificationDB.h"
#import "YSNavigationController.h"

#define TabbarVC    @"vc"
#define TabbarTitle @"title"
#define TabbarImage @"image"
#define TabbarSelectedImage @"selectedImage"
#define TabbarItemBadgeValue @"badgeValue"
#define TabBarCount 4

typedef NS_ENUM(NSInteger,YSMainTabType) {
    YSMainTabTypeDial,           //拨号
    YSMainTabTypeChat,           //聊天
    YSMainTabTypeContacts,       //联系人
    YSMainTabTypeMe,             //我的
};

@interface YSMainTabBarController()<NIMSystemNotificationManagerDelegate,NIMConversationManagerDelegate>
@property (nonatomic,strong) NSArray *navigationHandlers;


@property (nonatomic,assign) NSInteger sessionUnreadCount;

@property (nonatomic,assign) NSInteger systemUnreadCount;

@property (nonatomic,assign) NSInteger customSystemUnreadCount;

@property (nonatomic,copy)  NSDictionary *configs;

@end
@implementation YSMainTabBarController

+ (instancetype)instance{
    
    UIViewController *vc = [UIApplication sharedApplication].delegate.window.rootViewController;
    if ([vc isKindOfClass:[YSMainTabBarController class]]) {
        return (YSMainTabBarController *)vc;
    }else{
        return nil;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupSubNav];
    [[NIMSDK sharedSDK].systemNotificationManager addDelegate:self];
    [[NIMSDK sharedSDK].conversationManager addDelegate:self];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setUpStatusBar];
}

- (void)viewWillLayoutSubviews {
    self.view.frame = [UIScreen mainScreen].bounds;
}

- (void)dealloc{
    [[NIMSDK sharedSDK].systemNotificationManager removeDelegate:self];
    [[NIMSDK sharedSDK].conversationManager removeDelegate:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (NSArray *)tabbars {
    self.sessionUnreadCount  = [NIMSDK sharedSDK].conversationManager.allUnreadCount;
    self.systemUnreadCount   = [NIMSDK sharedSDK].systemNotificationManager.allUnreadCount;
    self.customSystemUnreadCount = [[YSCustomNotificationDB sharedInstance] unreadCount];
    NSMutableArray *items = [[NSMutableArray alloc] init];
    for (NSInteger tabbar = 0; tabbar < TabBarCount; tabbar++) {
        [items addObject:@(tabbar)];
    }
    return items;
}
- (void)setupSubNav {
    NSMutableArray *handleArray = [[NSMutableArray alloc] init];
    NSMutableArray *vcArray = [[NSMutableArray alloc] init];
    [self.tabbars enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDictionary * item =[self vcInfoForTabType:[obj integerValue]];
        NSString *vcName = item[TabbarVC];
        NSString *title  = item[TabbarTitle];
        NSString *imageName = item[TabbarImage];
        NSString *imageSelected = item[TabbarSelectedImage];
        Class clazz = NSClassFromString(vcName);
        UIViewController *vc = [[clazz alloc] initWithNibName:nil bundle:nil];
        vc.hidesBottomBarWhenPushed = NO;
        YSNavigationController *nav = [[YSNavigationController alloc] initWithRootViewController:vc];
        nav.tabBarItem = [[UITabBarItem alloc] initWithTitle:title
                                                       image:[UIImage imageNamed:imageName]
                                               selectedImage:[UIImage imageNamed:imageSelected]];
        nav.tabBarItem.tag = idx;
        NSInteger badge = [item[TabbarItemBadgeValue] integerValue];
        if (badge) {
            nav.tabBarItem.badgeValue = [NSString stringWithFormat:@"%zd",badge];
        }
        YSNavigationHandler *handler = [[YSNavigationHandler alloc] initWithNavigationController:nav];
        nav.delegate = handler;
        
        [vcArray addObject:nav];
        [handleArray addObject:handler];
    }];
    self.viewControllers = [NSArray arrayWithArray:vcArray];
    self.navigationHandlers = [NSArray arrayWithArray:handleArray];
    
}

- (void)setUpStatusBar{
    UIStatusBarStyle style = UIStatusBarStyleDefault;
    [[UIApplication sharedApplication] setStatusBarStyle:style
                                                animated:NO];
}

#pragma mark - NIMConversationManagerDelegate
- (void)didAddRecentSession:(NIMRecentSession *)recentSession
           totalUnreadCount:(NSInteger)totalUnreadCount{
    self.sessionUnreadCount = totalUnreadCount;
    [self refreshSessionBadge];
}


- (void)didUpdateRecentSession:(NIMRecentSession *)recentSession
              totalUnreadCount:(NSInteger)totalUnreadCount{
    self.sessionUnreadCount = totalUnreadCount;
    [self refreshSessionBadge];
}


- (void)didRemoveRecentSession:(NIMRecentSession *)recentSession totalUnreadCount:(NSInteger)totalUnreadCount{
    self.sessionUnreadCount = totalUnreadCount;
    [self refreshSessionBadge];
}

- (void)messagesDeletedInSession:(NIMSession *)session{
    self.sessionUnreadCount = [NIMSDK sharedSDK].conversationManager.allUnreadCount;
    [self refreshSessionBadge];
}

- (void)allMessagesDeleted{
    self.sessionUnreadCount = 0;
    [self refreshSessionBadge];
}


#pragma mark - NIMSystemNotificationManagerDelegate
- (void)onSystemNotificationCountChanged:(NSInteger)unreadCount
{
    self.systemUnreadCount = unreadCount;
    [self refreshContactBadge];
}

#pragma mark - Notification
- (void)onCustomNotifyChanged:(NSNotification *)notification
{
    YSCustomNotificationDB *db = [YSCustomNotificationDB sharedInstance];
    self.customSystemUnreadCount = db.unreadCount;
    [self refreshSettingBadge];
}

- (void)refreshSessionBadge{
    UINavigationController *nav = self.viewControllers[YSMainTabTypeDial];
    nav.tabBarItem.badgeValue = self.sessionUnreadCount ? @(self.sessionUnreadCount).stringValue : nil;
}

- (void)refreshContactBadge{
    UINavigationController *nav = self.viewControllers[YSMainTabTypeChat];
    NSInteger badge = self.systemUnreadCount;
    nav.tabBarItem.badgeValue = badge ? @(badge).stringValue : nil;
}

- (void)refreshSettingBadge{
    UINavigationController *nav = self.viewControllers[YSMainTabTypeMe];
    NSInteger badge = self.customSystemUnreadCount;
    nav.tabBarItem.badgeValue = badge ? @(badge).stringValue : nil;
}


- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

#pragma mark - NTESNavigationGestureHandlerDataSource
- (UINavigationController *)navigationController
{
    return self.selectedViewController;
}

#pragma mark - VC
- (NSDictionary *)vcInfoForTabType:(YSMainTabType)type{
    
    if (_configs == nil)
    {
        _configs = @{
                     @(YSMainTabTypeDial) : @{
                             TabbarVC           : @"YSDialViewController",
                             TabbarTitle        : @"拨号",
                             TabbarImage        : @"",
                             TabbarSelectedImage: @"",
                             TabbarItemBadgeValue: @(self.sessionUnreadCount)
                             },
                     @(YSMainTabTypeChat)     : @{
                             TabbarVC           : @"YSSessionListViewController",
                             TabbarTitle        : @"聊天",
                             TabbarImage        : @"",
                             TabbarSelectedImage: @"",
                             TabbarItemBadgeValue: @(self.systemUnreadCount)
                             },
                     @(YSMainTabTypeContacts): @{
                             TabbarVC           : @"YSContactsViewController",
                             TabbarTitle        : @"联系人",
                             TabbarImage        : @"",
                             TabbarSelectedImage: @"",
                             },
                     @(YSMainTabTypeMe)     : @{
                             TabbarVC           : @"YSMeViewController",
                             TabbarTitle        : @"我的",
                             TabbarImage        : @"",
                             TabbarSelectedImage: @"",
                             TabbarItemBadgeValue: @(self.customSystemUnreadCount)
                             }
                     };
        
    }
    return _configs[@(type)];
}

@end
